<template>
  <el-dialog v-model="isDialogVisible" title="编辑名称" @close="handleCancel" ref="dialogRef">
    <el-form :model="formData" label-width="80px">
      <el-form-item label="状态值">
        <el-input v-model="formData.nodeState" ref="inputRef"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleOk">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, onMounted, onBeforeUnmount } from 'vue';
import { useVModel } from '@vueuse/core';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  initial: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['ok', 'cancel', 'update:visible']);

const isDialogVisible = useVModel(props, 'visible', emit);

const formData = reactive({ ...props.initial });

const inputRef = ref(null);

const focusInput = ref(false);

watch(() => props.visible, (newVal) => {
  isDialogVisible.value = newVal;
  if (newVal) {
    // 重新设置 form 对象的初始值
    Object.assign(formData, props.initial);
    focusInput.value = true;
  }
});

watch(isDialogVisible, (newVal) => {
  if (!newVal) {
    emit('cancel');
  }
});

onMounted(() => {
  if (focusInput.value && inputRef.value) {
    inputRef.value.focus();
  }
});

const handleOk = () => {
  emit('ok', formData);
  handleCancel();
};

const handleCancel = () => {
  isDialogVisible.value = false;
};
</script>

<style scoped>
/* 添加一些样式 */
</style>